import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { ArcgisApiService } from '../arcgisapi.service';
import { loadModules, } from "esri-loader";
@Component({
  selector: 'app-esrimap',
  templateUrl: './esrimap.page.html',
  styleUrls: ['./esrimap.page.scss'],
})
export class EsrimapPage implements OnInit {
  mapCenter = [121.31, 30.35];
  basemapType = 'satellite';
  mapZoomLevel = 12;

  @ViewChild("mapViewNode", { static: true }) private mapViewEl: ElementRef;
  map: any;
  mapView: any;
  constructor(private arcgisService: ArcgisApiService) { }
  featureLayer: any;
  graphicsLayer: any;
  baseurl = "http://10.80.4.8:6080/";
  ngOnInit() {
    this.initmap();
  }
  ngOnDestroy() {
    if (this.mapView) {
      this.mapView.container = null;
    }
  }

  initmap() {
    this.arcgisService.loaded$.subscribe(loaded => {
      if (loaded) {
        this.arcgisService.constructMap({
          basemap: "",
          // ground: "world-elevation", // s
          elevation: false
        }).then(map => {
          this.map = map;

          // this.arcgisService.constructSceneView({
          //   map: map,
          //   container: this.mapViewEl.nativeElement,
          //   center: [119.15, 36.71],
          //   // camera: {
          //   //   position: {  // observation point
          //   //     x: -118.80800,
          //   //     y: 33.96100,
          //   //     z: 25000 // altitude in meters
          //   //   },
          //   //   tilt: 65  // perspective in degrees
          //   // },
          //   // scale: 100000,
          //   // center: [7645705.22, 675449.87],
          //   zoom: 13,
          // }).then(sceneView => {
          //   console.log("constructSceneView");
          //   this.mapView = sceneView;
          // });





          this.arcgisService.constructMapView(
            {
              map: map,
              container: this.mapViewEl.nativeElement,
              // center: [119.15, 36.71],
              center: [113.39332352487594, 34.53926278102739],
              // 34.54557723010144-=-=---113.39970924803806
              // 113.39332352487594---34.53926278102739
              zoom: 13,
            }
          ).then(mapView => {
            console.log("constructSceneView");
            this.mapView = mapView
            this.initclick();
            // this.arcgisService.mercatorTolonlat({
            //   lat: '77.46925659365',
            //   lon: '116.9736298868',
            // }
            // ).then(
            //   outputpoints => {

            //     alert("经度：" + outputpoints[0].x + ",纬度：" + outputpoints[0].y);//返回的也是几何类型的数组，这里是点的数组
            //   }
            // )
          })
          // this.arcgisService.constructWebTileLayers([{
          //   url: 'http://{subDomain}.tianditu.gov.cn/vec_c/wmts',
          //   layername: 'vec',
          //   tileMatrixSet: 'c'
          // }, {
          //   url: 'http://{subDomain}.tianditu.gov.cn/cva_c/wmts',
          //   layername: 'cva',
          //   tileMatrixSet: 'c',
          // }]).then(featureLayers => {
          //   for (var i in featureLayers) {
          //     map.add(featureLayers[i]);
          //   }
          // })
          this.arcgisService.constructWebTileLayer({
            url: 'http://t0.tianditu.com/vec_w/wmts',

            layername: 'vec',
            tileMatrixSet: 'w'
          }
          ).then(
            featureLayer => {
              this.featureLayer = featureLayer;
              map.add(featureLayer, 0);

            }
          )
          this.arcgisService.constructWebTileLayer({
            url: 'http://t0.tianditu.com/cva_w/wmts',
            layername: 'cva',
            tileMatrixSet: 'w',
          }
          ).then(
            featureLayer => {
              this.featureLayer = featureLayer;
              map.add(featureLayer, 1);

            }
          )
          // this.arcgisService.constructMapImageLayer({
          //   // url: this.baseurl + "arcgis/rest/services/py/image/MapServer",
          //   url: 'https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer'
          // })
          //   .then(featureLayer => {
          //     this.featureLayer = featureLayer;
          //     map.add(featureLayer, 0);

          //   });

          // const popupTemplate = { //设置弹出框样式
          //   // autocasts as new PopupTemplate()
          //   title: "属性查询",
          //   content: [
          //     {
          //       type: "fields",
          //       fieldInfos: [ //属性标示
          //         {
          //           fieldName: "起始点号",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         },
          //         {
          //           fieldName: "终止点号",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         },
          //         {
          //           fieldName: "起点高程",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         },
          //         {
          //           fieldName: "起点埋深",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         }, {
          //           fieldName: "终点高程",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         }, {
          //           fieldName: "终点埋深",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         }, {
          //           fieldName: "管径",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         },
          //         {
          //           fieldName: "管线材料",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         },
          //         {
          //           fieldName: "埋设方式",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         },
          //         {
          //           fieldName: "压力",
          //           label: "FEAT_CMNT",
          //           format: {
          //             places: 0,
          //             digitSeparator: true
          //           }
          //         }
          //       ]
          //     }
          //   ]
          // };
          const popupTemplate = { //设置弹出框样式
            // autocasts as new PopupTemplate()
            title: "属性查询",
            content: [
              {
                type: "fields",
                fieldInfos: [ //属性标示
                  {
                    fieldName: "ADDNAME",
                    label: "地址",
                    format: {
                      places: 0,

                      digitSeparator: true
                    }
                  },
                  {
                    fieldName: "NAME",
                    label: "名称",
                    format: {
                      places: 0,

                      digitSeparator: true
                    }
                  },
                  {
                    fieldName: "NEWNAME1",
                    label: "新名称",
                    format: {
                      places: 0,

                      digitSeparator: true
                    }
                  }

                ]
              }
            ]
          };
          // this.arcgisService.constructFeatureLayer({
          //   url: this.baseurl + "arcgis/rest/services/%E5%8C%97%E6%B5%B7%E9%81%93%E8%A1%97%E9%81%93%E5%90%8D%E5%9C%B0%E5%9D%80/MapServer",
          //   // url: 'https://services5.arcgis.com/WhEPAYSA6CoybLvO/arcgis/rest/services/三维场景1211_WFL1/FeatureServer/0',
          //   // url: 'https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0',
          //   outFields: ["*"], // 返回所有属性
          //   popupTemplate: popupTemplate,
          // })
          //   .then(featureLayer => {
          //     console.log("constructFeatureLayer");
          //     // this.mapView = mapView
          //     var featureLayer1: any = featureLayer;
          //     featureLayer1.popupEnabled = true;//不可查询
          //     map.add(featureLayer);
          //   });
          // this.arcgisService.constructFeatureLayer({
          //   url: this.baseurl + "arcgis/rest/services/py/管线/MapServer/1",
          //   outFields: ["*"], // used by queryFeatures
          //   popupTemplate: popupTemplate,
          // })
          //   .then(featureLayer => {
          //     // console.log("constructSceneView");
          //     // this.mapView = mapView
          //     var featureLayer2: any = featureLayer;
          //     // featureLayer2.popupEnabled = false;
          //     map.add(featureLayer, 2);

          //   });

        })
      }
    })

  }
  initclick() {
    var that = this;
    this.mapView.on("click", function (event) {
      // queryFeatureLayer(event.mapPoint, 1500, "intersects");
      console.log("click");
      console.log(event.mapPoint);
      var point = event.mapPoint;
      // that.queryFeatureLayer(event.mapPoint, 150, "intersects", "");
      alert("经度-" + point.latitude + "纬度-" + point.longitude);
    });
  }
  queryFeatureLayer(featureLayer, point, distance, spatialRelationship, sqlExpression) {
    var query = {
      geometry: point,
      distance: distance,
      spatialRelationship: spatialRelationship,
      outFields: ["*"],
      returnGeometry: true,
      where: sqlExpression
    };
    featureLayer.queryFeatures(query).then((result) => {

      this.addGraphics(result);
    });
  }
  addGraphics(result) {
    loadModules([' esri/layers/GraphicsLayer', 'esri/Graphic'])
      .then(([GraphicsLayer, Graphic]) => {
        if (this.graphicsLayer === undefined) {
          this.graphicsLayer = new GraphicsLayer();
          this.map.add(this.graphicsLayer);
        }

        this.graphicsLayer.removeAll();
        result.features.forEach(function (feature) {
          var g = new Graphic({
            geometry: feature.geometry,
            attributes: feature.attributes,
            symbol: {
              type: "simple-marker",
              color: [0, 0, 0],
              outline: {
                width: 2,
                color: [0, 255, 255],
              },
              size: "20px"
            },
            popupTemplate: {
              title: "{TRL_NAME}",
              content: "This a {PARK_NAME} trail located in {CITY_JUR}."
            }
          });
          this.graphicsLayer.add(g);
        });

      });

  }
}

